package com.wrb.pwd.service;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.wrb.pwd.model.User;

import java.io.*;
import java.net.URISyntaxException;
import java.net.URL;
import java.net.URLDecoder;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardCopyOption;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author wrb
 * @date 2019/9/16 13:59
 */
public class UserService {

	public static final String DATA_FILE_NAME = "user_db.json";

	/**
	 * 查看用户密码列表
	 *
	 * @return
	 */
	public List<User> getUserList(String platform) {
		List<User> userList = readJsonFile();
		List<User> filterList = userList;
		if (platform != null && !"".equals(platform.trim())) {
			filterList = userList.stream().filter(p -> p.getPlatform() != null && p.getPlatform().contains(platform)).collect(Collectors.toList());
		}
		return filterList;
	}

	/**
	 * 新增一个用户信息
	 *
	 * @param user
	 * @return
	 */
	public boolean insertUser(User user) {
		List<User> userList = readJsonFile();
		userList.add(user);
		String jsonStr = JSON.toJSONString(userList);
		return setJsonStrToFile(jsonStr);
	}

	/**
	 * 通过 id 删除 user
	 *
	 * @param id
	 * @return
	 */
	public boolean deleteUser(String id) {
		List<User> userList = readJsonFile();
		List<User> filterList = userList.stream().filter(p -> !id.equals(p.getId())).collect(Collectors.toList());
		String jsonStr = JSON.toJSONString(filterList);
		return setJsonStrToFile(jsonStr);
	}

	private List<User> readJsonFile() {
		StringBuilder jsonStrs = new StringBuilder();
		BufferedReader reader = null;
		InputStream is = null;
		try {
//			File file = ResourceUtils.getFile(jsonFilePath);
//			if (!file.exists()) {
//				throw new IllegalArgumentException("json文件不存在");
//			}
			String jarPath = this.getClass().getProtectionDomain().getCodeSource().getLocation().getPath();
			jarPath = URLDecoder.decode(jarPath, "utf-8");
			File file = new File(jarPath.substring(0, jarPath.lastIndexOf("/")) + "/" + DATA_FILE_NAME);
			is = new FileInputStream(file);
			InputStreamReader inputStreamReader = new InputStreamReader(is, "UTF-8");
			reader = new BufferedReader(inputStreamReader);
			String tempStr = null;
			while ((tempStr = reader.readLine()) != null) {
				jsonStrs.append(tempStr);
			}
		} catch (IOException e) {
			e.printStackTrace();
			throw new IllegalArgumentException("处理json文件流错误");
		} finally {
			if (reader != null) {
				try {
					reader.close();
				} catch (IOException e) {
					throw new IllegalArgumentException("处理json文件流错误1");
				}
			}
			if (is != null) {
				try {
					is.close();
				} catch (IOException e) {
					throw new IllegalArgumentException("处理json文件流错误2");
				}
			}
		}
		List<User> userList = JSONArray.parseArray(jsonStrs.toString().trim(), User.class);
		if (userList == null || userList.isEmpty()) {
			userList = new ArrayList<>();
		}
		return userList;
	}

	private boolean setJsonStrToFile(String jsonStr) {
		Writer fw;
		try {
			String jarPath = this.getClass().getProtectionDomain().getCodeSource().getLocation().getPath();
			jarPath = URLDecoder.decode(jarPath, "utf-8");
			//新建一个文件对象，如果不存在则创建一个该文件
			File f = new File(jarPath.substring(0, jarPath.lastIndexOf("/")) + "/" + DATA_FILE_NAME);
			fw = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(f), "UTF-8"));
			//将字符串写入到指定的路径下的文件中
			fw.write(jsonStr);
			fw.close();
			return true;
		} catch (IOException e) {
			System.out.println(e.getMessage());
			return false;
		}
	}

	/**
	 * 把jar内部的资源文件导出到外部路径
	 * TODO 可加密文件内容
	 *
	 * @return
	 * 0. 运行失败
	 * 1. 运行成功
	 * 2. 运行成功并备份文件
	 */
	public int setResourceFileToLocation() {
		InputStream in = null;
		FileOutputStream fos = null;
		int result = 1;
		try {
			in = this.getClass().getResourceAsStream("/" + DATA_FILE_NAME);
			String jarPath = this.getClass().getProtectionDomain().getCodeSource().getLocation().getPath();
			jarPath = URLDecoder.decode(jarPath, "utf-8");
			File f = new File(jarPath.substring(0, jarPath.lastIndexOf("/")) + "/" + DATA_FILE_NAME);
			//如果文件存在 则把文件添加后缀备份
			if (f.exists()) {
				File bakFile = new File(jarPath.substring(0, jarPath.lastIndexOf("/")) + "/" + DATA_FILE_NAME + "." + System.currentTimeMillis());
				boolean rename = f.renameTo(bakFile);
				if (!rename) {
					return 0;
				}
				result = 2;
			}
			int index;
			byte[] bytes = new byte[8192];
			fos = new FileOutputStream(f);
			while ((index = in.read(bytes)) != -1) {
				fos.write(bytes, 0, index);
				fos.flush();
			}
			return result;
		} catch (Exception e) {
			e.printStackTrace();
			return 0;
		} finally {
			if (in != null) {
				try {
					in.close();
				} catch (IOException e) {
					System.out.println("in关闭失败");
				}
			}
			if (fos != null) {
				try {
					fos.close();
				} catch (IOException e) {
					System.out.println("fos关闭失败");
				}
			}
		}
	}

}
